package com.atguigu.eduservice.controller;


import com.atguigu.commonutils.R;
import com.atguigu.eduservice.client.VodClient;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author Lei Deng
 * @since 2021-12-24
 */
@Api(tags = "视频管理")
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {


    @Autowired
    private EduVideoService videoService;

    /**
     * 注入vodClient
     */
    @Autowired
    private VodClient vodClient;
    /**
     * 添加小节
     */
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo) {
        videoService.save(eduVideo);
        return R.ok();
    }

    /**
     * 删除小节的时候删除阿里云视频
     */
    @DeleteMapping("{id}")
    public R deleteVideo(@PathVariable String id) {
        //根据视频id，远程调用实现视频删除
        String videoSourceId = videoService.getById(id).getVideoSourceId();
        if (!StringUtils.isEmpty(videoSourceId)) {
            R result = vodClient.removeAliyunVideo(videoSourceId);
            if (result.getCode() == 20001) {
                throw new GuliException(20001, "删除视频失败，熔断器Hystrix。。。");
            }
        }
        //先删视频再删小节
        videoService.removeById(id);
        return R.ok();

    }


    /**
     * 修改小节 ,回显
     */

    @GetMapping("/getVideoInfo/{id}")
    public R getVideoInfo(@PathVariable String id) {
        EduVideo eduVideo = videoService.getById(id);
        return R.ok().data("eduVideo", eduVideo);
    }

    /**
     * 修改
     */
    @PostMapping("updateVideo")
    public R updateVideoInfo(@RequestBody EduVideo eduVideo) {
        videoService.updateById(eduVideo);
        return R.ok();
    }
}

